package com.way.filemanager.navigation;

import hwdroid.widget.ActionBar.ActionBarView;
import hwdroid.widget.ActionBar.ActionBarView.OnRightWidgetItemClick;
import hwdroid.widget.FooterBar.FooterBarItem;

import java.io.File;
import java.util.LinkedList;
import java.util.Locale;

import com.way.filemanager.R;
import com.way.filemanager.navigation.MyFileManager.FileChangeListener;
import com.way.filemanager.navigation.MyFileManager.FileListener;
import com.way.filemanager.navigation.NavigationListFragmant.Mode;
import com.way.filemanager.util.AndroidHelper;
import com.way.filemanager.util.CommonFunc;
import com.way.filemanager.util.ScrollOverListView;
import com.way.filemanager.util.ScrollOverListView.OnScrollOverListener;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.BaseAdapter;
import android.widget.AdapterView;
import android.widget.ImageView.ScaleType;

public class MyAdapter extends BaseAdapter implements AdapterView.OnItemClickListener
    , FileChangeListener, AdapterView.OnItemLongClickListener
{
    private static final String TAG = "MyAdapter";
    private static final boolean DEBUG = true;

    private class FileItem
    {
        File file;
        boolean selected;
    }

    private MyFileManager fm;
    private FileItem[] mFiles;

    private Context mContext = null;

    private boolean mIsSelectMode;

    private ActionBarView mActionBarView;
    private FooterBarItem mFooterBarSelectButton;
    private CheckBox mSelectAllCheckBox;
    private FileListener mLongClickFileListener;
    private FileChangeListener mFileChangeListener;
    private ScrollOverListView mListView;
    private ImageView mSearchButton;
    private View.OnClickListener mSearchButtonClickListner;

    private Mode mMode = Mode.normal;
    private View mNoItemSearchHintView;
    private boolean mIsSearching;
    private class ViewHolder implements CompoundButton.OnCheckedChangeListener
    {
        ImageView icon;
        MyItemTextView title;
        TextView text;
        ImageView imageView;
        CheckBox checkbox;
        ViewGroup rightWidget;
        FileItem fileItem;

        public ViewHolder(ViewGroup v)
        {
            icon = (ImageView) v.findViewById(R.id.hw_drawable);
            title = (MyItemTextView) v.findViewById(R.id.hw_text);
            text = (TextView) v.findViewById(R.id.hw_subtext);
            rightWidget = (ViewGroup) v.findViewById(R.id.hw_right_widget_frame);
            v.setTag(this);
        }

        public void clearRight()
        {
            rightWidget.removeAllViews();
        }

        public void setRightCheckBox()
        {
            if(checkbox == null)
            {
                clearRight();
                checkbox = new CheckBox(mContext);
                rightWidget.addView(checkbox);
                checkbox.setFocusable(false);
                if(mMode == Mode.getcontext)
                {
                    checkbox.setClickable(false);
                }
            }
            else
            {
                if(rightWidget.getChildCount() > 0)
                {
                    if(! (rightWidget.getChildAt(0) instanceof CheckBox))
                    {
                        clearRight();
                        rightWidget.addView(checkbox);
                    }
                }
                else
                {
                    rightWidget.addView(checkbox);
                }
            }

            checkbox.setChecked(fileItem.selected);
            checkbox.setOnCheckedChangeListener(this);
        }

        public void setRightImage(Drawable d)
        {
            if(d == null)
            {
                clearRight();
            }
            else
            {
                if(imageView == null)
                {
                    clearRight();
                    imageView = new ImageView(mContext);
                    imageView.setImageDrawable(d);
                    rightWidget.addView(imageView);
                }
                else
                {
                    if(rightWidget.getChildCount() > 0)
                    {
                        if(! (rightWidget.getChildAt(0) instanceof ImageView))
                        {
                            clearRight();
                            imageView.setImageDrawable(d);
                            rightWidget.addView(imageView);
                        }
                    }
                    else
                    {
                        imageView.setImageDrawable(d);
                        rightWidget.addView(imageView);
                    }
                }
            }
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            fileItem.selected = isChecked;
            updateSelectTitle();
        }
    }

    public MyAdapter(Context c, View v,MyFileManager in_fm)
    {
        mNoItemSearchHintView = v.findViewById(R.id.noitemhint);
        ScrollOverListView lv = (ScrollOverListView) (v.findViewById(R.id.list));

        fm = in_fm;//MyFileManager.getFm();
        files2Item(fm.getFiles());
        mContext = c;
        mListView = lv;

        lv.setAdapter(this);
        lv.setOnItemClickListener(this);
        lv.setOnItemLongClickListener(this);

        mListView.setOnScrollOverListener(mOnScrollOverListener);

        fm.setCacheIconCb(new FileChangeListener()
        {
            @Override
            public void onChanged()
            {
                notifyDataSetChanged();
            }
        });
    }

    public void setActionBarView(ActionBarView actionBarView)
    {
        mActionBarView = actionBarView;
    }

    public void setLongClickFileListener(FileListener l)
    {
        mLongClickFileListener = l;
    }

    public void setFileChangeListener(FileChangeListener l)
    {
        mFileChangeListener = l;
    }

    public void setFooterBarSelectButton(FooterBarItem item)
    {
        mFooterBarSelectButton = item;
    }

    public void setSearchButtonClickListener(View.OnClickListener l)
    {
        mSearchButtonClickListner = l;
    }

    private void ensureSearchButton()
    {
        mSearchButton = new ImageView(mContext);
        mSearchButton.setPadding(0, 10, 0, 10);
        mSearchButton.setImageResource(R.drawable.hw_ic_search_normal);
        mSearchButton.setScaleType(ScaleType.CENTER);
        mSearchButton.setMinimumHeight((int)AndroidHelper.convertDpToPixel(mContext, 50));

        mSearchButton.setOnClickListener(mSearchButtonClickListner);
    }

    OnScrollOverListener mOnScrollOverListener = new OnScrollOverListener()
    {
        @Override public boolean onListViewTopAndPullDown(MotionEvent event, int delta)
        {
            if(fm.isCurrentRoot() == false && shouldShowSearch() && (delta > 20))
            {
                ensureSearchButton();
                mIsSearchShown = true;
                notifyDataSetChanged();
            }
            return false;
        }
        @Override public boolean onListViewBottomAndPullUp(MotionEvent event, int delta) { return false; }
        @Override public boolean onMotionDown(MotionEvent ev) { return false; }
        @Override public boolean onMotionMove(MotionEvent ev, int delta) { return false; }
        @Override public boolean onMotionUp(MotionEvent ev) { return false; }
    };

    public void onDestroy()
    {
        mActionBarView = null;
        mFooterBarSelectButton = null;
        mLongClickFileListener = null;
        mFileChangeListener = null;
        mSelectAllCheckBox = null;
    }

    public void setSearchView(SearchView s)
    {
        //bug110878
        mFilterText = null;
        s.setOnQueryTextListener(new SearchView.OnQueryTextListener()
        {
            @Override
            public boolean onQueryTextChange(String newText)
            {
                MyFileManager.log("on text "+newText);
                if(newText != null && newText.length() > 0)
                {
                    mFilterText = newText.toLowerCase(Locale.getDefault());
                }
                else
                    mFilterText = null;
                updateFilteredItems();
                return false;
            }
            @Override public boolean onQueryTextSubmit(String query) { return false; }
        });
        //bug110878
        updateFilteredItems();
    }
    public interface SearchCancel
    {
        void cancelSearchMode();
    }
    SearchCancel mSearchCancel = null;
    public void setSearchCancel(SearchCancel s)
    {
        mIsSearching = true;
        mSearchCancel = s;
    }
    public void setSearchMode(boolean mod)
    {
        mIsSearching = mod;
    }
    public void setSelectAll(CheckBox cb)
    {
        mSelectAllCheckBox = cb;
        mActionBarView.setOnRightWidgetItemClickListener(new OnRightWidgetItemClick(){

            @Override
            public void onRightWidgetItemClick() {
                // TODO Auto-generated method stub
                onSelectAll();
                CommonFunc.TA_Click(CommonFunc.OnClick_Delete_All);
            }
        });
    }

    private void onSelectAll()
    {
        if(null != mSelectAllCheckBox)
        {
            boolean checked = !mSelectAllCheckBox.isChecked();
            for(FileItem f : mFiles)
            {
                f.selected = checked;
            }

            notifyDataSetChanged();
            updateSelectTitle();
        }
    }

    public void setMode(Mode m)
    {
        mMode = m;

        boolean oldSelect = mIsSelectMode;
        mIsSelectMode = (m == Mode.select);
        if(mIsSelectMode)
        {
            if(oldSelect == false)
            {
                for(FileItem f :mFiles)
                {
                    f.selected = false;
                }
                if(mFooterBarSelectButton != null)
                {
                    mFooterBarSelectButton.setEnabled(false);
                }

                if(null != mSelectAllCheckBox)
                {
                    mSelectAllCheckBox.setChecked(false);
                }
            }
            else
            {
                mIsSearchShown = false;
                notifyDataSetChanged();
                return;
            }

        }

        mIsSearchShown = false;
        files2Item(fm.getFiles());
        notifyDataSetChanged();
    }

    public boolean onBackPressed()
    {
        if(fm.goUpFolder())
        {
            return true;
        }
        return false;

    }

    @Override public int getCount() { return getFilteredItemsSize(); }
    @Override public Object getItem(int position) { return getFilteredItem(position); }
    @Override public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        if(position == 0 && (canShowSearch()))
        {
            return mSearchButton;
        }

        ViewHolder vh = null;
        if(!(convertView == null || convertView ==  mSearchButton))
        {
            vh = (ViewHolder) convertView.getTag();
        }
        
        if(vh == null)
        {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = (ViewGroup)(inflater.inflate(R.layout.navigation_list_item, null));
            vh = new ViewHolder((ViewGroup)convertView);
        }

        FileItem fi = getFilteredItem(position);
        if(fi == null)
        {
            return convertView;
        }

        File file = fi.file;
        vh.fileItem = fi;
        boolean isDirectory = file.isDirectory();
        Resources r = mContext.getResources();
        if(isDirectory)
        {
            vh.icon.setImageDrawable(null);
            vh.icon.setVisibility(View.GONE);
            File[] files = file.listFiles();
            if(files != null && files.length > 0)
            {
                vh.text.setText(Utils.createTimeFormat(file.lastModified())
                        + " " + files.length + r.getText(R.string.ali_item));
            }
            else
            {
                vh.text.setText(Utils.createTimeFormat(file.lastModified()) + " " + r.getText(R.string.ali_emptyfolder));
            }
            vh.title.setTitle(file.getName(), fm.getFolderSubTitle(file), vh.text);
        }
        else
        {
            String name = file.getName();
            vh.icon.setVisibility(View.VISIBLE);
            vh.icon.setImageDrawable(fm.getFileIcon(name, file));
            vh.text.setText(Utils.createTimeFormat(file.lastModified()) + " "+ Utils.formetFileSize(file.length()));
            vh.setRightImage(null);
            vh.title.setTitle(name, null, null);
        }

        if(file.isHidden())
        {
            convertView.setAlpha(0.5f);
        }
        else
        {
            convertView.setAlpha(1f);
        }
        if(mMode == Mode.getcontext)
        {
            if(isDirectory)
            {
                vh.setRightImage(mContext.getResources().getDrawable(R.drawable.ic_list_enter));
            }
            else
            {
                vh.setRightCheckBox();
                //vh.checkbox.setChecked(vh.fileItem.selected);
            }
        }
        else if(!mIsSelectMode)
        {
            if(isDirectory)
            {
                vh.setRightImage(mContext.getResources().getDrawable(R.drawable.ic_list_enter));
            }
            else
            {
                vh.setRightImage(null);
            }
        }
        else
        {
            vh.setRightCheckBox();
        }

        return convertView;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
    {
        if(view == mSearchButton)
        {
            return;
        }

        ViewHolder vh = (ViewHolder)view.getTag();
        if(mMode == Mode.getcontext)
        {
            if(vh.fileItem.file.isDirectory())
            {
                fm.onFileClicked(mContext, vh.fileItem.file);
            }
            else
            {
                for(FileItem f : mFiles)
                {
                    if(vh.fileItem != f)
                    {
                        f.selected =false;
                    }
                }

                vh.fileItem.selected = !vh.fileItem.selected;
                //if(vh.checkbox != null)
                //    vh.checkbox.setChecked(vh.fileItem.selected);
                updateSelectTitle();
                notifyDataSetChanged();
            }
        }
        else if(mIsSelectMode)
        {
            vh.fileItem.selected = !vh.fileItem.selected;
            if(vh.checkbox != null)
                vh.checkbox.setChecked(vh.fileItem.selected);
            updateSelectTitle();
        }
        else if(mIsSearching)
        {

            mSearchCancel.cancelSearchMode();
            fm.onFileClicked(mContext, vh.fileItem.file);
        }
        else
        {
            fm.onFileClicked(mContext, vh.fileItem.file);
        }
    }

    @Override
    public void onChanged()
    {
        if(mFileChangeListener != null)
        {
            mFileChangeListener.onChanged();
        }

        if(mIsSelectMode)
        {
            return;
        }

        if(mIsSearchShown && fm.isCurrentRoot())
        {
            mIsSearchShown = false;
        }

        files2Item(fm.getFiles());
        if(mMode == Mode.getcontext)
           updateSelectTitle();
        notifyDataSetChanged();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
    {
        final File file = ((ViewHolder)arg1.getTag()).fileItem.file;
        if(fm.isCurrentRoot() == false && file != null && mLongClickFileListener != null)
        {
            mLongClickFileListener.onFile(file);
        }
        return true;
    }
    private void files2Item(File[] files)
    {
        mFiles = null;
        int len = files.length;
        mFiles = new FileItem[len];
        for(int i = 0;i < len;i++)
        {
            mFiles[i] = new FileItem();
            mFiles[i].file = files[i];
        }
        updateFilteredItems();
    }

    private void updateSelectTitle()
    {
        if(null != mActionBarView)
        {
            int count = 0;
            boolean isAllSelected = true;
            for(FileItem f : mFiles)
            {
                if(f.selected)
                    count++;
                else
                    isAllSelected = false;
            }

            mActionBarView.setTitle(mContext.getResources().getQuantityString(
                    R.plurals.numberOfSelected, 1, count));
            if(mSelectAllCheckBox!=null)
                mSelectAllCheckBox.setChecked(isAllSelected);
            if(mFooterBarSelectButton != null)
            {
                mFooterBarSelectButton.setEnabled(count != 0);
                if(mFooterBarSelectButton.getItemTitle().equals(mContext.getResources().getString(R.string.actions_menu_delete)))
                {
                    if(count == 0)
                        mFooterBarSelectButton.setItemTextColor(Color.GRAY);
                    else
                        mFooterBarSelectButton.setItemTextColor(Color.RED);
                }
                else
                {
                    if(count == 0)
                        mFooterBarSelectButton.setItemTextColor(Color.GRAY);
                    else
                        mFooterBarSelectButton.setItemTextColor(mContext.getResources().getColor(R.color.button_text_color_ok));
                }
            }

        }
    }

    public LinkedList<File> getSelectedFiles()
    {
        LinkedList<File> files = new LinkedList<File>();
        for(FileItem f : mFiles)
        {
            if(f.selected)
            {
                files.add(f.file);
            }
        }
        return files;
    }

    private int getFilteredItemsSize()
    {
        mNoItemSearchHintView.setVisibility(View.INVISIBLE);
        mListView.setVisibility(View.VISIBLE);

        if(canShowSearch())
        {
            return mFiles.length + 1;
        }

        if(mMode != Mode.search)
        {
            if(mFiles.length < 1)
                RefreshNoFileItemShow(false);
            return mFiles.length;
        }

        if(mFilteredItems.size() == 0)
        {
            RefreshNoFileItemShow(true);
        }

        return mFilteredItems.size();
    }
    //BugID:104186:add empty wording
    private void RefreshNoFileItemShow(boolean isSearch)
    {
        TextView mtext;
        mtext = (TextView)mNoItemSearchHintView;
        mNoItemSearchHintView.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.INVISIBLE);
        if(isSearch)
        {
            mtext.setCompoundDrawables(null, null, null, null);
            mtext.setText(R.string.No_item_Searched);
        }
        else
        {
            Drawable drawable= mContext.getResources().getDrawable(R.drawable.ic_file_empty_normal);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mtext.setCompoundDrawables(null, drawable, null, null);
            mtext.setCompoundDrawablePadding((int)AndroidHelper.convertDpToPixel(mContext, 24));
            mtext.setGravity(Gravity.CENTER);
            mtext.setText(R.string.No_item_display);
        }
    }
    private FileItem getFilteredItem(int index)
    {
        if(canShowSearch())
        {
            if(index > 0)
                return mFiles[index- 1];
            else
                return mFiles[index];
        }

        if(mMode != Mode.search)
            return mFiles[index];
        return mFilteredItems.get(index);
    }

    private LinkedList<FileItem> mFilteredItems = new LinkedList<FileItem>();
    private String mFilterText;
    private boolean mIsSearchShown;

    private boolean shouldShowSearch()
    {
        if(mMode == Mode.normal && mIsSearchShown == false)
        {
            return true;
        }
        return false;
    }

    private boolean canShowSearch()
    {
        if(mMode == Mode.normal && mIsSearchShown == true)
        {
            return true;
        }
        return false;
    }


    private void updateFilteredItems()
    {
        mFilteredItems.clear();

        for(FileItem fi : mFiles)
        {
            if(mFilterText == null || fi.file.getName().toLowerCase(Locale.getDefault()).contains((mFilterText)))
            {
                mFilteredItems.add(fi);
            }
        }
        notifyDataSetChanged();
    }

}
